package main

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
	"github.com/sirupsen/logrus"
	"io/ioutil"
	"os"
	"os/exec"
)

func main() {
	irisEngine := iris.New()
	loader := NewServiceLoader(irisEngine)
	loader.RegisterAPIs(RegisterAPIsProc)
	loader.Run(ServiceLoaderRunningOption{ListenPort: 8000})

}

type ServiceLoaderRunningOption struct {
	ListenPort int
}

func (l *ServiceLoader) Run(option ServiceLoaderRunningOption) {
	err := l.irisEngine.Run(iris.Addr(fmt.Sprintf("0.0.0.0:%d", option.ListenPort)))
	if err != nil {
		logrus.Fatalf("API引擎启动失败，具体错误: %s", err.Error())
		return
	}
}
func RegisterAPIsProc(irisEngine *iris.Application) error {
	//middlewares := []context.Handler{loaders.Cors, loaders.RecoverHandler}
	app := irisEngine.Party("/test").AllowMethods(iris.MethodOptions)
	app.Get("/start", DeployDownload)
	app.Get("/cao", Nima)
	return nil
}
func Nima(ctx context.Context) {
	file, err := ioutil.ReadFile("file/nacos.sql")
	if err != nil {
		ctx.JSON(err.Error())
		return
	}
	ctx.JSON(string(file))

}

func DeployDownload(ctx context.Context) {
	storeName := os.Getenv("name")
	switch storeName {
	case "mysql":
		os.Setenv("MYSQL_PWD", "mysql")
		args := fmt.Sprintf("mysql -h %s -u%s  -P %s mysql < %s", "10.136.104.54", "root", 3307, "file/nacos.sql")
		cmd := exec.Command("/bin/bash", "-c", args)
		err := cmd.Start()
		if err != nil {
			logrus.Error(err)
		}
		output, _ := cmd.Output()
		logrus.Println(output)
		return
	case "postgresql":
		os.Setenv("PGPASSWORD ", "postgres")
		arg := fmt.Sprintf("psql -h %s -U%s -p %s -f %s", "10.136.104.54", "postgres", 8432, "file/kong.sql")
		cmd := exec.Command("/bin/bash", "-c", arg)
		err := cmd.Start()
		if err != nil {
			logrus.Error(err)
		}
		output, _ := cmd.Output()
		logrus.Println(output)
		return
	default:
		return
	}
	ctx.JSON("wanshile")

}

func NewServiceLoader(irisEngine *iris.Application) *ServiceLoader {
	return &ServiceLoader{
		irisEngine: irisEngine,
	}
}

type ServiceLoader struct {
	irisEngine *iris.Application
}

func (l *ServiceLoader) RegisterAPIs(proc func(irisEngine *iris.Application) error) {
	if proc == nil {
		logrus.Fatal("API路由注册函数不能为空!")
		return
	}
	err := proc(l.irisEngine)
	if err != nil {
		logrus.Fatalf("API路由注册失败，具体错误: %s", err.Error())
		return
	}
}
